<?php
/**
 * Desc:
 * User: zdb
 * Date: 2024/7/29
 * Time: 16:51
 */
namespace app\api\service;

use app\api\model\library\LibPoetModel;
use app\api\model\library\LibPoemModel;
use app\api\service\resource\LibMovieSubtitleService;
use app\util\DateUtil;
use sqhlib\Hanzi\HanziConvert;
use think\facade\Db;

class LibraryService
{
    const ARR_RESOURCE_TYPE = array('poem' => 'poem', 'movie_en_word' => 'movie_en_word');
    /**
     * Desc: 存储唐诗三百首
     * Datetime: 2024/7/29 16:51 by zdb
     */
    public function insertThreeHundredPoem()
    {
        $file = "D://wamp/www/memory/example/file/300.json";
        $jsonData = file_get_contents($file);
        $list = json_decode($jsonData, true);
        $libPoemModel = new LibPoemModel();
        $i = 0;
        foreach($list as $item){
            $data = [
                'poem_type_text' => $item['type'] ?? '',
                'poem_title' => $item['title'] ?? '',
                'poet' => $item['author'] ?? '',
                'poem_content' => $item['contents'] ?? '',
            ];
            $res = $libPoemModel->addOne($data);
            if($res){
                $i++;
            }else{
                echo $item['title']."<br>";
            }
        }
        echo "<br>Insert Total:".$i;
    }

    public function insertJsonPoem()
    {
        $file = "D://poem/poems4.json";

        $libPoemModel = new LibPoemModel();
        $i = 0;
        $handle = fopen($file, "r"); // 打开文件
        if ($handle) {
            while (($line = fgets($handle)) !== false) { // 每次读取一行内容
                try{
                    $item = json_decode($line, true);
                    $data = array();
                    if(!empty($item["content"])){
                        $data['poem_content'] = implode("\n", $item["content"]);
                    }
                    if(!empty($item["translate"])){
                        $data['translation'] = implode("\n", $item["translate"]);
                    }
                    if(!empty($item["notes"])){
                        $data['annotation'] = implode("\n", $item["notes"]);
                    }

                    if(!empty($item["appreciation"])){
                        $data['appreciation'] = implode("\n", $item["appreciation"]);
                    }

                    if(!empty($item["reference"])){
                        $data['background'] = implode("\n", $item["reference"]);
                    }

                    if(!empty($item["tags"])){
                        $data['poem_tag'] =  implode(";", $item["tags"]);
                    }

                    $data['dynasty'] = str_replace('代', '', $item["dynasty"]);
                    $data['poet'] = $item["author"];
                    $data['poem_title'] = $item["name"];
                    $data['poem_type_text'] = $item["format"];
                    $data['source_link'] = $item["sourceLink"];

                    $data['outer_id'] =  $item["_id"]['$oid'];
                    $data['status'] =  1;
                    $data['create_time'] = DateUtil::getCurrentDatetime();
                    $res = $libPoemModel->insertOne($data);
                    if($res){
                        $i++;
                    }else{
                        echo $item['name']."<br>";
                    }
                }catch(\Exception){
                    echo $item['name']."<br>";
                }
            }
            fclose($handle); // 关闭文件
        }
        echo "<br>Insert Total:".$i;
    }

    public function insertTangPoet()
    {
        $file = "D://wamp/www/memory/example/file/authors.tang.json";
        $jsonData = file_get_contents($file);
        $list = json_decode($jsonData, true);
        $libPoetModel = new LibPoetModel();
        $i = 0;
        foreach($list as $item){
            $data = [
                'name' => HanziConvert::convert($item['name']) ?? '',
                'dynasty' => '唐',
                'description' => HanziConvert::convert($item['desc']) ?? '',
            ];
            $res = $libPoetModel->addOne($data);
            if($res){
                $i++;
            }else{
                echo $item['name']."<br>";
            }
        }
        echo "<br>Insert Total:".$i;
    }

    public function insertSongPoet()
    {
        $file = "D://wamp/www/memory/example/file/authors.song.json";
        $jsonData = file_get_contents($file);
        $list = json_decode($jsonData, true);
        $libPoetModel = new LibPoetModel();
        $i = 0;
        foreach($list as $item){
            $data = [
                'name' => HanziConvert::convert($item['name']) ?? '',
                'dynasty' => '宋',
                'descriptin' => HanziConvert::convert($item['desc']) ?? '',
            ];
            $res = $libPoetModel->addOne($data);
            if($res){
                $i++;
            }else{
                echo $item['name']."<br>";
            }
        }
        echo "<br>Insert Total:".$i;
    }

    /**
     * Desc: 10-考研   12-托福   9-雅思  4-大学四级 6-大学六级  8-专八
     *
     * Datetime: 2024/10/15 7:33 by zdb
     */
    public function insertEnWordPhrase()
    {
        $arrSpeechType = array(
            'n' => 1,
            'noun' => 1,
            'pron' => 2,
            'art' => 3,
            'adj' => 4,
            'a' => 4,
            'adv' => 5,
            'ad' => 5,
            'v' => 6,
            'vt' => 6,
            'vi' => 7,
            'num' => 8,
            'prep' => 9,
            'conj' => 10,
            'int' => 11,
        );

        $file = "E://wamp64/www/memory/example/file/12_vocabulary_en.json";
        $jsonData = file_get_contents($file);
        $list = json_decode($jsonData, true);

        $i = 0;
//        $target = 1000;
        try{
//            Db::starttrans();
            foreach($list as $index => $item){
                $data = [
                    'spelling' => isset($item['word']) ? $item['word']:'',
                    'status' => 1,
                    'update_time' => date("Y-m-d H:i:s")
                ];
                $wordId = Db::table('yj_lib_word_en')->duplicate($data)->insert($data, true);
//                if($i == 4){
//                    echo $wordId;exit;
//                }
                foreach($item['translations'] as $speechItem){
                    $speechItem['type'] = empty($speechItem['type']) ? 'v':$speechItem['type'];
                    $arrType = explode("&", $speechItem['type']);
                    foreach($arrType as $singleType){
                        $addData2 = array(
                            'word_id' => $wordId,
                            'part_of_speech' => $arrSpeechType[$singleType] ?? 1,
                            'speech_text' => $singleType,
                            'update_time' => date("Y-m-d H:i:s")
                        );
                        $newTypeId = Db::table('yj_lib_word_en_type')->duplicate($addData2)->insert($addData2, true);

                        //同一种词性，可能有多种不同的意思
                        $arrMeaning = explode("；", $speechItem['translation']);
                        $addData3 = array();
                        foreach($arrMeaning as $meaningVal){
                            if(empty($meaningVal)){
                                continue;
                            }
                            $addData3[] = array(
                                'word_type_id' => $newTypeId,
                                'meaning_en' => '',
                                'meaning_cn' => $meaningVal,
                            );
                        }
                        if(!empty($addData3)){
                            Db::table('yj_lib_word_en_meaning')->insertAll($addData3);
                        }
                    }
                }
                if(isset($item['phrases'])){
                    foreach($item['phrases'] as $phraseItem){
                        if(empty( $phraseItem['phrase'] )){
                            continue;
                        }
                        $addDataPhrase = array(
                            'word_id' => $wordId,
                            'phrase' => $phraseItem['phrase'] ?? '',
                            'meaning_en' => '',
                            'meaning_cn' => $phraseItem['translation'],
                        );
                        $newPhraseId = Db::table('yj_lib_word_en_phrase')->insert($addDataPhrase, true);
                    }
                }
                $i++;
//                if($i == $target){
//                    break;
//                }
            }
//            Db::commit();
            echo "<br>Insert Total:".$i;
        }catch(\Exception $e){
//            Db::rollback();
            echo "disruppt:".$list[$index]['word'];
            echo $e->getMessage();
        }

    }

    public function deconstructSubtitle()
    {
        $file = "F://subtitle/Atonement_2007_English-ELSUBTITLE.COM-ST_49819686.srt";

//        $file = "F://subtitle/Ghost.1990.Bluray.720p.x264.AC3.2Audios-CMCT.srt";
        $file = "F://subtitle/The.Notebook.2004.BluRay.1080p.TrueHD5.1.x264-beAst.eng.srt";
        $file = "F://subtitle/Gone.Girl.2014.1080p.BluRay.x264-SPARKS.eng.srt";
        $file = "F://subtitle/Rebecca.1940.BluRay.1080p.x264.DTS.3Audios-CMCT.eng.srt";
        $file = "F://subtitle/Titanic.1997.Blu-ray.1080p.x264.DTS.DD51.DD20.MultiAudio.MySilu.eng.srt";
        $file = "F://subtitle/The.Shawshank.Redemption.1994.1080p.BluRay.x264.10bit-WiKi.eng.srt";
        $file = "F://subtitle/Ice.Age.1.2002.BluRay.en.srt";
//        $file = "F://subtitle/Detachment.2011.1080p.BluRay.x264.DTS-FGT.eng.srt";
//        $file = "F://subtitle/Orphan (2009) REMUX.eng.srt";
        $file = "F://subtitle/The.Truman.Show.1998.1080p.BluRay.x265-RARBG.HBOGO.ENG.SRT";
        $file = "F://subtitle/The.Reader.2008.1080p.BluRay.x264-CiNEFiLE.English.srt";
        $file = "F://subtitle/The.Bridges.of.Madison.County.1995.720p.BluRay.x264-HD4U.eng.srt.srt";
        $file = "F://subtitle/Out.Of.Africa.1985.BluRay.1080p.DTS.2Audio.x264-CHD.eng.srt";
        $file = "F://subtitle/Edward.Scissorhands.1990.REMASTERED.1080p.BluRay.X264-AMIABLE.eng.srt";
        $file = "F://subtitle/Pride.and.Prejudice.2005.1080p.BluRay.x265-RARBG.srt";
        $file = "F://subtitle/Gone.with.the.Wind.1939.1080p.BluRay.x264-WiKi.eng.srt";
        $file = "F://subtitle/The Curious Case of Benjamin Button 2008 BDRip 1080 DTS HighCode.English.srt";
        $file = "F://subtitle/Dead.Poets.Society.1989.1080p.BluRay.x264.DTS-WiKi.eng.srt";





        $fp = fopen($file, 'r');
        $i = 0;
        $movieId = 21;
        if($fp){
            $rowData = array();
            $serviceSubtitle = new LibMovieSubtitleService();
            $lineCount = 1;
            while( ($line = fgets($fp)) !== false ){
                $line = trim($line);
                if(is_numeric($line)){
                    //写入上一条数据
                    if(!empty($rowData['time_point_start'])){
                        $rowData['movie_id'] = $movieId;
                        $rowData['subtitle_lang'] = 'en';
                        $serviceSubtitle->createRow($rowData);
                        $lineCount++;
                    }
                    $rowData = array();
                    $rowData['seq_index'] = $lineCount;
                }else if(false !== strpos($line, '-->')){
                    $arrTime = explode('-->', $line);
                    $rowData['time_point_start'] = $arrTime[0];
                    $rowData['time_point_end'] = $arrTime[1] ?? '';
                }else{
                    //字幕内容
                    if(!empty($rowData['subtitle'])){
                        $rowData['subtitle'] .= "\n".$line;
                    }else{
                        $rowData['subtitle'] = $line;
                    }
                }
                $i++;
            }
            fclose($fp);
            echo "total line:".$i;
        }
    }

    /**
     * 导入中文字幕
     */
    public function importChineseSubtitle()
    {
        $file = "F://subtitle/Dead.Poets.Society.1989.BluRay.720p.x264.AC3.CHD.Chs.srt";

        $fp = fopen($file, 'r');
        $i = 0;
        $movieId = 21;
        if($fp){
            $rowData = array();
            $seqIndex = 1;
            $serviceSubtitle = new LibMovieSubtitleService();
            while( ($line = fgets($fp)) !== false ){
                $line = trim($line);
                if(is_numeric($line)){
                    //写入上一条数据
                    if(!empty($rowData['seq_index'])){
                        $rowData['movie_id'] = $movieId;
                        $rowData['subtitle_lang'] = 'cn';
                        $serviceSubtitle->createRow($rowData);
                    }
                    $rowData = array();
                }else if(false !== strpos($line, '-->')){
                    $arrTime = explode('-->', $line);
                    //根据时间，找到英文字幕对应的seq_index
                    $info = $serviceSubtitle->findMatchedSubtitle($movieId, $arrTime);
                    if(empty($info)){
                        continue;
                    }
                    $blankNum = $info['seq_index'] - $seqIndex;
//                    echo "current seq:".$info['seq_index'].", last seq:".$seqIndex.", --blank num:".$blankNum."<br>";
                    //弥补空行
                    for($j=1; $j<$blankNum; $j++){
                        $rowData = array();
                        $seqIndex = $seqIndex + $j;
                        $supplementInfo = $serviceSubtitle->findRowByData(array('seq_index' => $seqIndex, 'movie_id' => $movieId));
                        $rowData['time_point_start'] = $supplementInfo['time_point_start'];
                        $rowData['time_point_end'] = $supplementInfo['time_point_end'];
                        $rowData['start_microsecond'] = $supplementInfo['start_microsecond'];
                        $rowData['end_microsecond'] = $supplementInfo['end_microsecond'];
                        $rowData['seq_index'] = $seqIndex;
                        $rowData['movie_id'] = $movieId;
                        $rowData['subtitle_lang'] = 'cn';
                        $serviceSubtitle->createRow($rowData);
                    }
                    $rowData = array();
                    $rowData['time_point_start'] = $info['time_point_start'];
                    $rowData['time_point_end'] = $info['time_point_end'];
                    $rowData['start_microsecond'] = $info['start_microsecond'];
                    $rowData['end_microsecond'] = $info['end_microsecond'];
                    $rowData['seq_index'] = $info['seq_index'];
                    $seqIndex = $info['seq_index'];
                }else{
                    //字幕内容
                    if(!empty($rowData['subtitle'])){
                        $rowData['subtitle'] .= "\n".$line;
                    }else{
                        $rowData['subtitle'] = $line;
                    }
                }
                $i++;
            }
            fclose($fp);
            echo "total line:".$i;
        }
    }

}